package com.macro.mall.tiny.modules.pms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.pms.dto.PmsRepairDataNode;
import com.macro.mall.tiny.modules.pms.model.PmsElectricMasterData;
import com.macro.mall.tiny.modules.pms.model.PmsRepairData;
import com.macro.mall.tiny.modules.pms.service.PmsRepairDataService;
import com.macro.mall.tiny.modules.pms.service.PmsUserActionService;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 维修数据管理控制器
 * </p>
 *
 * @author tyrone
 * @since 2025-02-20
 */
@RestController
@Api(tags = "PmsRepairDataController")
@RequestMapping("/pms/pmsRepairData")
@Tag(name = "PmsRepairDataController", description = "维修数据管理")
public class PmsRepairDataController {
    @Autowired
    private PmsRepairDataService pmsRepairDataService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("前台搜索接口")
    @GetMapping("/search")
    public CommonResult<List<PmsRepairData>> search(@ApiParam("搜索关键字") @RequestParam String keyword) {
        QueryChainWrapper<PmsRepairData> query = pmsRepairDataService.query();
        UmsMember member = MemberContext.getMember();
        if (member!=null){
            String key = "PmsRepairData:"+member.getId();
            // 删除重复记录
            redisTemplate.opsForList().remove(key, 0, keyword);
            // 添加到列表头部
            redisTemplate.opsForList().leftPush(key, keyword);
            // 限制列表长度
            redisTemplate.opsForList().trim(key, 0, 9);

        }
        query.eq("type", 1).like("name", keyword).orderByAsc("type");
        List<PmsRepairData> list = query.list();
        handlePrivacyData(list);
        return CommonResult.success(list);
    }

    @ApiOperation("添加维修数据")
    @PostMapping("/add")
    public CommonResult<Boolean> create(@RequestBody PmsRepairData pmsRepairData) {
        boolean success = pmsRepairDataService.save(pmsRepairData);
        if (success) {
            return CommonResult.success(true);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改维修数据")
    @PostMapping("/update")
    public CommonResult<Boolean> update( @RequestBody PmsRepairData pmsRepairData) {
        boolean success = pmsRepairDataService.updateById(pmsRepairData);
        if (success) {
            return CommonResult.success(true);
        }
        return CommonResult.failed();
    }



    @ApiOperation("后台批量删除数据")
    @PostMapping("/delete")
    public CommonResult<Boolean> delete(@RequestBody List<Long> ids) {
        boolean success = pmsRepairDataService.removeByIds(ids);
        if (success) {
            return CommonResult.success(true);
        }
        return CommonResult.failed();
    }

    @ApiOperation("根据ID获取维修数据详情")
    @GetMapping("/{id}")
    public CommonResult<PmsRepairData> getItem(@PathVariable Long id) {
        PmsRepairData pmsRepairData = pmsRepairDataService.getById(id);
        return CommonResult.success(pmsRepairData);
    }

    @ApiOperation("获取子类")
    @GetMapping("getSubItem")
    public CommonResult<PmsRepairDataVO> getCategoryAndItem(@ApiParam("当前分类id") @RequestParam Long id,
                                                            @ApiParam("排序类型 0创建时间 1浏览量 2收藏量") @RequestParam(required = false) Integer sortType) {
        QueryChainWrapper<PmsRepairData> query = pmsRepairDataService.query().eq("parent_id", id);

        List<PmsRepairData> list = query.list();
        List<PmsRepairData> directoryList = list.stream().filter(e -> e.getType() == 0).collect(Collectors.toList());
        List<PmsRepairData> fileList = list.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
        if (!fileList.isEmpty()) {
            if (sortType == null || sortType == 0) {
                fileList.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            } else if (sortType == 1) {
                fileList.sort((a, b) -> b.getViewNum().compareTo(a.getViewNum()));
            } else if (sortType == 2) {
                fileList.sort((a, b) -> b.getCollectNum().compareTo(a.getCollectNum()));
            }
        }
        handlePrivacyData(directoryList);
        handlePrivacyData(fileList);
        PmsRepairDataVO vo = new PmsRepairDataVO();
        vo.setDirectoryList(directoryList);
        vo.setFileList(fileList);
        return CommonResult.success(vo);
    }

    @ApiOperation("分页查询维修数据")
    @PostMapping("/page")
    public CommonResult<Page<PmsRepairData>> list(@RequestBody PmsRepairData pmsRepairData) {
        Page<PmsRepairData> pmsRepairDataPage = new Page<>(pmsRepairData.getPageNum(), pmsRepairData.getPageSize());
        QueryWrapper<PmsRepairData> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(pmsRepairData.getName())) {
            queryWrapper.like("name", pmsRepairData.getName());
        }
        if (pmsRepairData.getType() != null) {
            queryWrapper.eq("type", pmsRepairData.getType());
        }
        if (pmsRepairData.getParentId() != null) {
            queryWrapper.eq("parent_id", pmsRepairData.getParentId());
        }
        if (pmsRepairData.getShowStatus() != null) {
            queryWrapper.eq("show_status", pmsRepairData.getShowStatus());
        }
        if (pmsRepairData.getId() != null) {
            queryWrapper.eq("id", pmsRepairData.getId());
        }
        queryWrapper.orderByDesc("create_time").orderByAsc("sort");

        Page<PmsRepairData> page = pmsRepairDataService.page(pmsRepairDataPage, queryWrapper);
        return CommonResult.success(page);
    }

    @ApiOperation("获取所有维修数据树形结构")
    @GetMapping("/treeList")
    public CommonResult<List<PmsRepairDataNode>> treeList(@RequestParam(value = "type", required = false) Integer type) {
        List<PmsRepairDataNode> treeList = pmsRepairDataService.treeList(type);
        return CommonResult.success(treeList);
    }

    @ApiOperation("后台获取树形分类")
    @GetMapping("getTreeCategory")
    public CommonResult<List<PmsRepairData>> getTreeCategory() {
        List<PmsRepairData> list = pmsRepairDataService.query().eq("type", 0).list();
        Map<Long, PmsRepairData> repairDataMap = list.stream().collect(Collectors.toMap(PmsRepairData::getId, e -> e));
        List<PmsRepairData> treeData = list.stream().filter(e -> e.getParentId() == 0).collect(Collectors.toList());
        List<PmsRepairData> needMerge = list.stream().filter(e -> e.getParentId() != 0).collect(Collectors.toList());
        for (PmsRepairData pmsRepairData : needMerge) {
            PmsRepairData parent = repairDataMap.get(pmsRepairData.getParentId());
            if (parent != null) {
                if (parent.getChildren() == null) {
                    parent.setChildren(Lists.newArrayList(pmsRepairData));
                } else {
                    parent.getChildren().add(pmsRepairData);
                }
            }
        }
        return CommonResult.success(treeData);
    }

    @ApiOperation("修改维修数据显示状态")
    @PostMapping("/updateShowStatus/{id}")
    public CommonResult<Boolean> updateShowStatus(@PathVariable Long id, @RequestParam("showStatus") Integer showStatus) {
        boolean success = pmsRepairDataService.updateShowStatus(id, showStatus);
        if (success) {
            return CommonResult.success(true);
        }
        return CommonResult.failed();
    }

    @ApiOperation("更新排序")
    @PostMapping("/updateSort/{id}")
    public CommonResult<Boolean> updateSort(@PathVariable Long id, @RequestParam("sort") Integer sort) {
        boolean success = pmsRepairDataService.updateSort(id, sort);
        if (success) {
            return CommonResult.success(true);
        }
        return CommonResult.failed();
    }

    @ApiOperation("获取指定父ID下的所有子节点")
    @GetMapping("/children/{parentId}")
    public CommonResult<List<PmsRepairData>> getChildren(@PathVariable Long parentId) {
        List<PmsRepairData> children = pmsRepairDataService.listByParentId(parentId);
        return CommonResult.success(children);
    }

    @ApiOperation("前台增加浏览量")
    @GetMapping("addViewNum")
    public CommonResult<Void> addViewNum(@ApiParam("数据id") @RequestParam Long id) {
        pmsRepairDataService.update()
                .setSql("view_num = view_num + 1").eq("id", id).update();
        return CommonResult.success(null);
    }

    @ApiOperation("分页获取指定父ID下的所有子节点")
    @GetMapping("/children/{parentId}/page")
    public CommonResult<PmsRepairDataVO> getChildrenList(@PathVariable Long parentId,
                                                         @RequestParam(value = "keyword", required = false) String keyword,
                                                         @RequestParam(value = "sortType") Integer sortType) {

        List<PmsRepairData> list = pmsRepairDataService.list(new QueryWrapper<PmsRepairData>().eq("parent_id", parentId));
        List<PmsRepairData> directoryList = list.stream().filter(e -> e.getType() == 0).collect(Collectors.toList());
        List<PmsRepairData> fileList = list.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
        if (!fileList.isEmpty()) {
            if (sortType == null || sortType == 0) {
                fileList.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            } else if (sortType == 1) {
                fileList.sort((a, b) -> b.getViewNum().compareTo(a.getViewNum()));
            } else if (sortType == 2) {
                fileList.sort((a, b) -> b.getCollectNum().compareTo(a.getCollectNum()));
            }
        }
        handlePrivacyData(directoryList);
        handlePrivacyData(fileList);
        PmsRepairDataVO vo = new PmsRepairDataVO();
        vo.setDirectoryList(directoryList);
        vo.setFileList(fileList);
        return CommonResult.success(vo);
    }

    @Autowired

    private PmsUserActionService pmsUserActionService;

    private void handlePrivacyData(List<PmsRepairData> lists) {
        if (MemberContext.getMember() != null) {
            List<Object> objects = pmsUserActionService.listItem(3, 1);
            for (PmsRepairData data : lists) {
                if (objects.contains(data.getId().intValue())) {
                    data.setCurrentMemberCollect(1);
                } else {
                    data.setCurrentMemberCollect(0);
                }
            }
        }
    }

    @Data
    public class PmsRepairDataVO {
        @ApiModelProperty("文件夹类型")
        private List<PmsRepairData> directoryList;

        @ApiModelProperty("文件类型")
        private List<PmsRepairData> fileList;
    }
}

